package com.al.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.al.entity.User;
import com.al.repository.UserRepository;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
	
	private UserRepository userRepository = new UserRepository();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		switch(method) {
		case "add":
			String idStr = req.getParameter("id");
			String name = req.getParameter("name");
			String scoreStr = req.getParameter("score");
			Integer id = Integer.parseInt(idStr);
			Double score = Double.parseDouble(scoreStr);
			userRepository.add(id, name, score);
			break;
		case "update":
			idStr = req.getParameter("id");
			name = req.getParameter("name");
			scoreStr = req.getParameter("score");
			id = Integer.parseInt(idStr);
			score = Double.parseDouble(scoreStr);
			userRepository.update(id, name, score);
			break;
		}
		//更新list集合中的数据，返回视图和数据，重定向到user,走get方法即可
		resp.sendRedirect("/myweb007/user");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if(method == null) {
			method = "findAll";
		}
		switch(method) {
		case "findAll":
			//返回视图和数据
			List<User> list = userRepository.findAll();
			req.setAttribute("list", list);
			req.getRequestDispatcher("index.jsp").forward(req, resp);
			break;
		case "deleteById":
			String idStr = req.getParameter("id");
			Integer id = Integer.parseInt(idStr);
			userRepository.deleteById(id);
			resp.sendRedirect("/myweb007/user");
			break;
		case "findById":
			idStr = req.getParameter("id");
			id = Integer.parseInt(idStr);
			req.setAttribute("user", userRepository.findById(id));
			req.getRequestDispatcher("update.jsp").forward(req, resp);
			break;
		}
		
	}
}
